package activitys;

import io.web.JSONConnector;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import misc.BasewarsConfig;
import misc.Sha1;
import nl.preflag.basewars.R;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class RegisterActivity extends Activity implements OnClickListener
{	
	private Button 		btnSubmit;
	private Button		btnLogin;
	private EditText 	etUsername;
	private EditText	etEmail;
	private	EditText	etPassword;
	private EditText	etPasswordVerify;
	
	private JSONConnector jsonCon;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		
		jsonCon = new JSONConnector();
		
		this.findViews();
	}
	
	/**
	 * Find the views
	 */
	private void findViews()
	{
		btnSubmit = (Button) findViewById(R.id.registerSubmit);
		btnSubmit.setOnClickListener(this);
		
		btnLogin = (Button) findViewById(R.id.registerLogin);
		btnLogin.setOnClickListener(this); 
		
		etUsername = 	(EditText) findViewById(R.id.registerUsername);
		etEmail = 		(EditText) findViewById(R.id.registerEmail);
		etPassword = 	(EditText) findViewById(R.id.registerPassword);
		etPasswordVerify = (EditText) findViewById(R.id.registerPasswordVerify);
	}

	@Override
	public void onClick(View v) 
	{
		switch(v.getId())
		{
			case R.id.registerSubmit:
				
				// check if user fill in some stuff that doesn't belong there
				boolean error = false;
				Pattern p = Pattern.compile("[A-Za-z]$");
				Matcher m = p.matcher( this.etUsername.getText().toString() );
				if(!m.find())
				{
					error = true;
					etUsername.setTextColor(Color.RED);
				}else
				{
					etUsername.setTextColor(Color.BLACK);
				}
						
				p = Pattern.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
				m = p.matcher( this.etEmail.getText().toString() );
				if(!m.find())
				{
					error = true;
					etEmail.setTextColor(Color.RED);
				}else
				{
					etEmail.setTextColor(Color.BLACK);
				}
				
				p = Pattern.compile("^.{2,20}$");
				m = p.matcher( this.etPassword.getText().toString() );
				Matcher m2 = p.matcher( this.etPasswordVerify.getText().toString() );
				if(!m.find() || !m2.find() || !this.etPassword.getText().toString().equals(this.etPasswordVerify.getText().toString()) )
				{
					error = true;
					etPassword.setTextColor(Color.RED);
					etPasswordVerify.setTextColor(Color.RED);
				}else
				{
					etPassword.setTextColor(Color.BLACK);
					etPasswordVerify.setTextColor(Color.BLACK);
				}
				
				if(error == true)
				{
					Toast.makeText(this, "Gegevens zijn ongeldig", Toast.LENGTH_LONG).show();
				}else
				{
					String password = "";
					try {
						password  = Sha1.StringToSha1String(this.etPassword.getText().toString());
					} catch (Exception e1) {
						e1.printStackTrace();
					}
					
					List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
	                nameValuePairs.add( new BasicNameValuePair( "username", this.etUsername.getText().toString() ) );
	                nameValuePairs.add( new BasicNameValuePair("password", password ) );
	                nameValuePairs.add( new BasicNameValuePair( "email", this.etEmail.getText().toString() ) );
					
					jsonCon.setBaseUrl(BasewarsConfig.getApiBaseUrl());
					JSONObject JSONResponse = jsonCon.requestPostObject("register/", nameValuePairs);
					
					try {
						getSharedPreferences("programSettings",MODE_PRIVATE)
						.edit()
						.putString("userId", JSONResponse.getJSONObject("result").getString("id"))
						.commit();
					} catch (JSONException e) 
					{
						e.printStackTrace();
					}
					
					Intent intent = new Intent(this, BaseMapActivity.class);
					startActivity(intent);
					
					finish();
				}
			break;
			
			case R.id.registerLogin:
				Intent connect = new Intent(this, LoginActivity.class);
				startActivityForResult(connect, 0);
			break;
		}
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if(resultCode==2){
	        finish();
	    }
	}
}
